/*
 *    Copyright (c) 2018-2025, boss All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the boss developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: boss
 */

package com.hopes.bizz.poll.monitor.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hopes.bizz.poll.monitor.dto.PollMonitorSiteDTO;
import com.hopes.bizz.poll.monitor.dto.PollMonitorSiteExcelDTO;
import com.hopes.bizz.poll.monitor.entity.PollMonitorSiteEntity;
import com.hopes.bizz.poll.monitor.service.PollMonitorSiteService;
import com.hopes.bizz.poll.monitor.service.PollMonitorTypeService;
import com.hopes.bizz.poll.monitor.vo.PollMonitorSiteByIdVO;
import com.hopes.bizz.poll.monitor.vo.PollMonitorSiteExcelVO;
import com.hopes.boss.common.core.util.R;
import com.hopes.boss.common.excel.annotation.RequestExcel;
import com.hopes.boss.common.excel.annotation.ResponseExcel;
import com.hopes.boss.common.log.annotation.SysLog;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 监控点信息
 *
 * @author pig
 * @date 2023-05-19 13:28:48
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/monitorSite" )
@Tag(description = "monitorSite" , name = "监控点信息管理" )
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class PollMonitorSiteController {

    private final PollMonitorSiteService pollMonitorSiteService;
    private final PollMonitorTypeService pollMonitorTypeService;

    /**
     * 分页查询
     * @param page 分页对象
     * @param pollMonitorSite 监控点信息
     * @return
     */
    @Operation(summary = "分页查询" , description = "分页查询" )
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('poll_monitor_site_view')" )
    public R getpollMonitorSitePage(Page page, PollMonitorSiteDTO pollMonitorSite) {
        LambdaQueryWrapper<PollMonitorSiteEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Objects.nonNull(pollMonitorSite.getOrgId()), PollMonitorSiteEntity::getOrgId, pollMonitorSite.getOrgId());
        wrapper.eq(Objects.nonNull(pollMonitorSite.getTownId()), PollMonitorSiteEntity::getTownId, pollMonitorSite.getTownId());
//        wrapper.eq(PollMonitorSiteEntity::getIsUse, true);
		wrapper.eq(StrUtil.isNotBlank(pollMonitorSite.getMonitorType()),PollMonitorSiteEntity::getMonitorType,pollMonitorSite.getMonitorType());
		wrapper.like(StrUtil.isNotBlank(pollMonitorSite.getName()),PollMonitorSiteEntity::getName,pollMonitorSite.getName());
        wrapper.orderByAsc(Arrays.asList(PollMonitorSiteEntity::getOrgId, PollMonitorSiteEntity::getSortNum));

        if (Objects.nonNull(pollMonitorSite.getMonitorTypeMain())) {
            List<Integer> monitorTypeByMain = pollMonitorTypeService.getMonitorTypeByMain(pollMonitorSite.getMonitorTypeMain());
            wrapper.in(PollMonitorSiteEntity::getMonitorType, monitorTypeByMain);
        }

		return R.ok(pollMonitorSiteService.queryPage(page, wrapper));
    }

    @Operation(summary = "查询" , description = "查询" )
    @GetMapping("/list/{type}")
    @PreAuthorize("@pms.hasPermission('poll_monitor_site_view')" )
    public R getPollMonitorSiteList(@PathVariable("type") String type) {
        LambdaQueryWrapper<PollMonitorSiteEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PollMonitorSiteEntity::getIsUse, true);
        wrapper.eq(StringUtils.isNotEmpty(type),PollMonitorSiteEntity::getMonitorType,type).eq(PollMonitorSiteEntity::getDelFlag,"0");
        return R.ok(pollMonitorSiteService.list(wrapper));
    }

    @Operation(summary = "查询并以树状结构返回" , description = "查询并以树状结构返回" )
    @GetMapping("/listByMainType/{mainType}")
    @PreAuthorize("@pms.hasPermission('poll_monitor_site_view')" )
    public R getPollMonitorSiteListByMainType(@PathVariable("mainType") Integer mainType) {
        return R.ok(pollMonitorSiteService.getPollMonitorSiteListByMainType(mainType));
    }

    @Operation(summary = "查询" , description = "查询" )
    @GetMapping("/list")
    @PreAuthorize("@pms.hasPermission('poll_monitor_site_view')" )
    public R getPollMonitorSiteList(PollMonitorSiteDTO pollMonitorSite) {
        LambdaQueryWrapper<PollMonitorSiteEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PollMonitorSiteEntity::getIsUse, true);

        if (Objects.nonNull(pollMonitorSite.getMonitorTypeMain())) {
            List<Integer> monitorTypeByMain = pollMonitorTypeService.getMonitorTypeByMain(pollMonitorSite.getMonitorTypeMain());
            wrapper.in(PollMonitorSiteEntity::getMonitorType, monitorTypeByMain);
        }

        return R.ok(pollMonitorSiteService.list(wrapper));
    }

    /**
     * 通过id查询监控点信息
     * @param id id
     * @return R
     */
    @Operation(summary = "通过id查询" , description = "通过id查询" )
    @GetMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('poll_monitor_site_view')" )
    public R getById(@PathVariable("id" ) Long id) {
        PollMonitorSiteEntity entity = pollMonitorSiteService.getById(id);
        PollMonitorSiteByIdVO vo = new PollMonitorSiteByIdVO();
        BeanUtils.copyProperties(entity, vo);
        vo.setMonitorTypeMain(String.valueOf(pollMonitorTypeService.getMonitorTypeMainByType(Integer.valueOf(vo.getMonitorType()))));

        return R.ok(vo);
    }


    /**
     * 新增监控点信息
     * @param pollMonitorSite 监控点信息
     * @return R
     */
    @Operation(summary = "新增监控点信息" , description = "新增监控点信息" )
    @SysLog("新增监控点信息" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('poll_monitor_site_add')" )
    public R save(@RequestBody PollMonitorSiteEntity pollMonitorSite) {
        return R.ok(pollMonitorSiteService.save(pollMonitorSite));
    }

    /**
     * 修改监控点信息
     * @param pollMonitorSite 监控点信息
     * @return R
     */
    @Operation(summary = "修改监控点信息" , description = "修改监控点信息" )
    @SysLog("修改监控点信息" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('poll_monitor_site_edit')" )
    public R updateById(@RequestBody PollMonitorSiteEntity pollMonitorSite) {
        return R.ok(pollMonitorSiteService.updateById(pollMonitorSite));
    }

    /**
     * 通过id删除监控点信息
     * @param ids id列表
     * @return R
     */
    @Operation(summary = "通过id删除监控点信息" , description = "通过id删除监控点信息" )
    @SysLog("通过id删除监控点信息" )
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('poll_monitor_site_del')" )
    public R removeById(@RequestBody Long[] ids) {
        return R.ok(pollMonitorSiteService.removeBatchByIds(CollUtil.toList(ids)));
    }

    /**
     * 新增监控点信息
     * @param dto 关联监控点视频
     * @return R
     */
    @Operation(summary = "关联监控点视频" , description = "关联监控点视频" )
    @SysLog("关联监控点视频" )
    @PostMapping( "/associated")
    @PreAuthorize("@pms.hasPermission('poll_monitor_site_edit')" )
    public R association(@RequestBody PollMonitorSiteDTO dto) {
        UpdateWrapper<PollMonitorSiteEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",dto.toPO().getId());
        updateWrapper.set("video_ids",dto.toPO().getVideoIds());
        return R.ok(pollMonitorSiteService.update(updateWrapper));
    }

    /**
     * excel模板
     *
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/template")
    @PreAuthorize("@pms.hasPermission('poll_monitor_site_export')")
    public List<PollMonitorSiteExcelDTO> template() {
        return Collections.singletonList(new PollMonitorSiteExcelDTO());
    }

    /**
     * 导出excel 表格
     * @param pollMonitorSite 查询条件
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('poll_monitor_site_export')")
    public List<PollMonitorSiteExcelVO> export(PollMonitorSiteDTO pollMonitorSite) {
        final LambdaQueryWrapper<PollMonitorSiteEntity> wrapper = Wrappers.<PollMonitorSiteEntity>lambdaQuery()
                .eq(PollMonitorSiteEntity::getAqiFlag, Boolean.FALSE)
                .eq(Objects.nonNull(pollMonitorSite.getOrgId()), PollMonitorSiteEntity::getOrgId, pollMonitorSite.getOrgId())
                .eq(StrUtil.isNotBlank(pollMonitorSite.getMonitorType()), PollMonitorSiteEntity::getMonitorType, pollMonitorSite.getMonitorType())
                .eq(Objects.nonNull(pollMonitorSite.getTownId()), PollMonitorSiteEntity::getTownId, pollMonitorSite.getTownId())
                .like(StrUtil.isNotBlank(pollMonitorSite.getName()), PollMonitorSiteEntity::getName, pollMonitorSite.getName())
                .orderByAsc(Arrays.asList(PollMonitorSiteEntity::getOrgId, PollMonitorSiteEntity::getSortNum));

        if (Objects.nonNull(pollMonitorSite.getMonitorTypeMain())) {
            List<Integer> monitorTypeByMain = pollMonitorTypeService.getMonitorTypeByMain(pollMonitorSite.getMonitorTypeMain());
            wrapper.in(PollMonitorSiteEntity::getMonitorType, monitorTypeByMain);
        }

        return pollMonitorSiteService.exportExcel(pollMonitorSiteService.list(wrapper));
    }

    /**
     * 导入excel 表格
     * @param pollMonitorSiteExcelDtoList 查询条件
     * @param bindingResult 错误信息列表
     * @return ok fail
     */
    @PostMapping("/import")
    @PreAuthorize("@pms.hasPermission('poll_monitor_site_export')")
    public R importExcel(@RequestExcel List<PollMonitorSiteExcelDTO> pollMonitorSiteExcelDtoList, BindingResult bindingResult) {
        return pollMonitorSiteService.importExcel(pollMonitorSiteExcelDtoList, bindingResult);
    }
}
